# Copyright (c) 2023 orchy <orchy12@proton.me>
# This file is licensed under the MIT/Expat license.
# You should have received a copy of the license with this software, if not see
# https://spdx.org/licenses/MIT.html
import ../src/x1b

type
  TermColorKind = enum
    # tfs = two five six, i really dont want to type that much
    eight, tfs, rgb
  TermColor = object
    kind: TermColorKind
    color: int
  TermCell = object
    bgColor: TermColor = TermColor(kind: eight, color: 0)
    fgColor: TermColor = TermColor(kind: eight, color: 7)
    c: char = ' '

var term: array[24, array[80, TermCell]]
var
  cursorX: int
  cursorY: int
let str = readAll(stdin)

for y in countup(0, 23):
  for x in countup(0, 79):
    term[y][x] = TermCell()

for cmd in x1bParse(str):
  case cmd.kind
    of c:
      case cmd.c:
        of '\n':
          cursorX = 0
          cursorY += 1
        else:
          cursorX += 1
          term[cursorY][cursorX].c = cmd.c
    of csi:
      case cmd.csi.fun:
        of 'A':
          doAssert cmd.csi.args.len == 1, "csi A requires 1 argument"
          cursorY -= cmd.csi.args[0]
        of 'B':
          doAssert cmd.csi.args.len == 1, "csi B requires 1 argument"
          cursorY += cmd.csi.args[0]
        of 'C':
          doAssert cmd.csi.args.len == 1, "csi C requires 1 argument"
          cursorX += cmd.csi.args[0]
        of 'D':
          doAssert cmd.csi.args.len == 1, "csi D requires 1 argument"
          cursorX -= cmd.csi.args[0]
        of 'H', 'f':
          doAssert cmd.csi.args.len == 2, "csi H/f requires 1 argument"
          cursorY = cmd.csi.args[0]
          cursorX = cmd.csi.args[1]
        else:
          stderr.write "Unimplemented csi function: " & cmd.csi.fun & "\n"
    of direct:
      case cmd.direct:
        else:
          stderr.write "Unimplemented direct function: " & cmd.direct & "\n"

for y in term:
  for x in y:
    stdout.write x.c
  echo ""
